package com.xuan.friend.manager;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.xuan.common.core.constants.CacheConstants;
import com.xuan.common.core.enums.QuestionStatus;
import com.xuan.common.core.exception.BusinessException;
import com.xuan.common.redis.service.RedisService;
import com.xuan.friend.domain.question.Question;
import com.xuan.friend.domain.user.UserContest;
import com.xuan.friend.domain.user.UserSubmit;
import com.xuan.friend.mapper.question.QuestionMapper;
import com.xuan.friend.mapper.user.UserContestMapper;
import com.xuan.friend.mapper.user.UserSubmitMapper;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import java.util.List;
import java.util.Objects;

@Component
public class QuestionCacheManager {

    @Resource
    private RedisService redisService;

    @Resource
    private QuestionMapper questionMapper;

    @Resource
    private UserSubmitMapper userSubmitMapper;


    public Long getQuestionListSize() {
        return redisService.getListSize(CacheConstants.QUESTION_LIST_KEY);
    }



    public void refreshCache() {
        // 刷新顺序列表到 redis 中,按题目创建时间降序
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>()
                .select(Question::getQuestionId)
                .orderByDesc(Question::getCreateTime));
        List<Long> questionIdList = questionList.stream().map(Question::getQuestionId).toList();
        redisService.rightPushAll(CacheConstants.QUESTION_LIST_KEY, questionIdList);
    }


    public Long prevQuestion(Long questionId) {
        Long index = redisService.indexOfForList(CacheConstants.QUESTION_LIST_KEY, questionId);
        if (index == 0) {
            throw new BusinessException("当前已经是第一题了哦");
        }
        return redisService.indexForList(CacheConstants.QUESTION_LIST_KEY, index - 1, Long.class);
    }

    public Long nextQuestion(Long questionId) {
        Long index = redisService.indexOfForList(CacheConstants.QUESTION_LIST_KEY, questionId);
        long lastIndex = getQuestionListSize() - 1;
        if (index == lastIndex) {
            throw new BusinessException("当前已经是最后一题了哦");
        }
        return redisService.indexForList(CacheConstants.QUESTION_LIST_KEY, index + 1, Long.class);
    }

    public List<Long> getHotQuestionIdList() {
        List<Long> questionIdList = redisService.getCacheListByRange(CacheConstants.HOT_QUESTION_LIST_KEY, 0, -1, Long.class);
        if (CollectionUtil.isEmpty(questionIdList)) {
            PageHelper.startPage(1, 10);
            questionIdList = userSubmitMapper.listHotQuestionId();
            if (CollectionUtil.isNotEmpty(questionIdList)) {
                // TODO 设置过期时间
                redisService.rightPushAll(CacheConstants.HOT_QUESTION_LIST_KEY, questionIdList);
            }
        }
        return questionIdList;
    }


    public List<Long> getUserQuestionStatusList(Long userId, Integer status) {
        String questionStatusListKey = getUserQuestionStatusListKey(userId, status);
        List<Long> questionStatusIdList = redisService.getCacheListByRange(questionStatusListKey, 0, -1, Long.class);
        if (CollectionUtil.isEmpty(questionStatusIdList)) {
            refreshQuestionStatusCache(userId, status);
            questionStatusIdList = redisService.getCacheListByRange(questionStatusListKey, 0, -1, Long.class);
        }
        return questionStatusIdList;
    }


    private void refreshQuestionStatusCache(Long userId, Integer status) {
        // 从 tb_user_submit 表查询
        List<UserSubmit> userSubmitList = userSubmitMapper.selectList(new LambdaQueryWrapper<UserSubmit>()
                .select(UserSubmit::getQuestionId)
                .eq(UserSubmit::getUserId, userId)
                .isNull(UserSubmit::getContestId)
                .eq(UserSubmit::getPass, status));
        List<Long> questionIdList = userSubmitList.stream().map(UserSubmit::getQuestionId).toList();
        if (CollectionUtil.isEmpty(questionIdList)) {
            return;
        }

        // 往 redis 中插入数据并设置过期时间
        String questionStatusListKey = getUserQuestionStatusListKey(userId, status);
        redisService.rightPushAll(questionStatusListKey, questionIdList);
        redisService.expire(questionStatusListKey, CacheConstants.EXP);
    }


    private String getUserQuestionStatusListKey(Long userId, Integer status) {
        if (Objects.equals(status, QuestionStatus.PASSED.getValue())) {
            return CacheConstants.USER_QUESTION_PASS_LIST_KEY + userId;
        } else if (Objects.equals(status, QuestionStatus.FAILED.getValue())) {
            return CacheConstants.USER_QUESTION_FAIL_LIST_KEY + userId;
        }
        return "";
    }


}
